package mes

import (
	"context"
	"encoding/json"
	"ez/apps/mes/auto/mc"
	"gitee.com/dreamwood/ez-go/db/mgo"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type Flow struct {
	mgo.BaseDoc `bson:"-" json:"-"`
	Id          int64 `json:"id" bson:"id,omitempty"`

	Plan string `json:"plan" bson:"plan"` //计划

	Sn string `json:"sn" bson:"sn"` //条码

	Template *ProcessTemplate `json:"template" bson:"template"` //应用模板

	TemplateId int64 `json:"templateId" bson:"templateId"` //应用模板

	Papers []*Paper `json:"papers" bson:"papers"` //报工单

	CreateAt time.Time  `json:"createAt" bson:"createAt"`
	UpdateAt time.Time  `json:"updateAt" bson:"updateAt"`
	DeleteAt *time.Time `json:"deleteAt" bson:"deleteAt"`
}

func (this *Flow) DocName() string { return "Flow" }

func (this *Flow) GetId() int64 { return this.Id }

func (this *Flow) SetId(id int64) { this.Id = id }

func (this *Flow) Create() error {
	return this.GetFactory().Create(this)
}

func (this *Flow) Replace() error {
	return this.GetFactory().Replace(this)
}

func (this *Flow) Save() error {
	if this.Id == 0 {
		this.CreateAt = time.Now()
		this.UpdateAt = time.Now()
		return this.GetFactory().Create(this)
	} else {
		this.UpdateAt = time.Now()
		return this.GetFactory().Replace(this)
	}
}

// 伪删除
func (this *Flow) Delete() error {
	return this.GetFactory().Delete(this)
}

func (this *Flow) UnDelete() error {
	return this.GetFactory().UnDelete(this)
}

// 真删除
func (this *Flow) Destroy() error {
	return this.GetFactory().Destroy(this)
}

func (this *Flow) ToString() string {
	return string(this.ToBytes())
}

func (this *Flow) ToBytes() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Flow) Serialize() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Flow) UnSerialize(data []byte) []byte {
	ez.Try(json.Unmarshal(data, this))
	return data
}

func (this *Flow) LoadTemplate() {
	if this.TemplateId == 0 {
		return
	}
	this.Template, _ = NewProcessTemplateCrud().FindId(this.TemplateId)
}

func (this *Flow) LoadPapers() {
	papers, _ := NewPaperCrud().FindBy(ss.M{"flowId": this.Id}, []string{"id"}, 0, 0)
	this.Papers = papers
}

func (this *Flow) ClearRelationsBeforeSave() mgo.Doc {

	this.Template = nil

	this.Papers = nil

	return this
}

func neverUsed_Flow() {
	//导入ss包
	a := ss.M{}
	ez.Debug(a)
}

type FlowAccessControl struct {
	Access  bool
	Message string
	Action  string //控制器Action,小写开头，如c,u,r,d
	Model   *Flow
	Session *ez.Session
}

func NewFlowAccessControl(model *Flow, action string, session *ez.Session) *FlowAccessControl {
	ctrl := &FlowAccessControl{
		Access:  true,
		Model:   model,
		Action:  action,
		Session: session,
	}
	ez.DispatchToMany(mc.FlowAccessControlEvent, ctrl, context.TODO())
	return ctrl
}
